package org.usmile.algorithms.leetcode.middle;

import java.util.ArrayList;
import java.util.List;

/**
 * 22. 括号生成
 *
 * 数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。
 *
 * 示例 1：
 * 输入：n = 3
 * 输出：["((()))","(()())","(())()","()(())","()()()"]
 *
 * 示例 2：
 * 输入：n = 1
 * 输出：["()"]
 *
 * 提示：
 * 1 <= n <= 8
 */
public class _0022 {
    public static void main(String[] args) {
        System.out.println(new _0022_Solution().generateParenthesis(2));
    }
}

class _0022_Solution {
    private List<String> result;
    private int n;

    public List<String> generateParenthesis(int n) {
        result = new ArrayList<>();
        this.n = n;

        dfs("", 0, 0);

        return result;
    }

    private void dfs(String path, int open, int close) {
        if (close > open || open > n) {
            return;
        }

        if (path.length() == 2 * n) {
            result.add(path);

            return;
        }

        dfs(path + "(", open + 1, close);
        dfs(path + ")", open, close + 1);
    }
}